#include "lcd_bl.h"
#include "bflb_gpio.h"
#include "bflb_core.h"
#include "bflb_pwm_v2.h"
#include "bflb_clock.h"
#include "config.h"

#define LCD_BL_PIN GPIO_PIN_2

struct bflb_device_s* pwm;
struct bflb_device_s* gpio;
static uint32_t pwm_period = PWM_PERIOD;

void lcd_bl_init()
{
    gpio = bflb_device_get_by_name("gpio");
    bflb_gpio_init(gpio, LCD_BL_PIN,
        GPIO_PULLUP | GPIO_OUTPUT | GPIO_FUNC_PWM0
        | GPIO_ALTERNATE | GPIO_SMT_EN | GPIO_DRV_1);

    bflb_gpio_set(gpio, LCD_BL_PIN);

    struct bflb_pwm_v2_config_s config = {
        .clk_source = BFLB_SYSTEM_XCLK,
        .clk_div = 40,
        .period = pwm_period,
    };
    pwm = bflb_device_get_by_name("pwm_v2_0");

    bflb_pwm_v2_init(pwm, &config);

    struct bflb_pwm_v2_channel_config_s cconfig =
    {
        .positive_polarity = PWM_POLARITY_ACTIVE_LOW,
        .negative_polarity = PWM_POLARITY_ACTIVE_LOW,
        .positive_stop_state = PWM_STATE_INACTIVE,
        .negative_stop_state = PWM_STATE_ACTIVE,
        .positive_brake_state = PWM_STATE_INACTIVE,
        .negative_brake_state = PWM_STATE_INACTIVE,
        .dead_time = 0,
    };

    bflb_pwm_v2_start(pwm);
    bflb_pwm_v2_channel_init(pwm, PWM_CH2, &cconfig);
    bflb_pwm_v2_channel_negative_start(pwm, PWM_CH2);
    bflb_pwm_v2_channel_positive_start(pwm, PWM_CH2);
    bflb_pwm_v2_channel_set_threshold(pwm, PWM_CH2, 0, pwm_period);

}

void lcd_bl_update_ligth(uint32_t value)
{
    uint32_t low, hig;
    hig = value * pwm_period / 100;
    low = pwm_period - hig;
    bflb_pwm_v2_channel_set_threshold(pwm, PWM_CH2, low, hig);
    printf("low: %d,hig: %d,b: %d\n", low, hig, value);
}
